package com.ctn.bootstarp.tags.util;

import tldgen.Function;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: weiqi
 * Date: 14-1-20
 * Time: 下午3:10
 * To change this template use File | Settings | File Templates.
 */
public class DateUtil {

    public static String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    public static String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final Date convertStringToDate(String strDate,String pattern) throws ParseException {
        SimpleDateFormat df = new SimpleDateFormat(pattern);
        Date date = df.parse(strDate);
        return (date);
    }

    public static final String convertDateToString(Date date,String pattern) {
        if (date == null) {
            return "date param is null!";
        } else {
            SimpleDateFormat df = new SimpleDateFormat(pattern);
            return  df.format(date);
        }
    }

    @Function
    public static String formatDateBypattern(Object date,String pattern){
        try {
            if(date instanceof String){
                Date d =  convertStringToDate((String)date,pattern);
                return convertDateToString(d,pattern);
            }
            else if(date instanceof Date){
                return convertDateToString((Date)date,pattern);
            }else{
                return "Param is not a date String or Date object!";
            }
        } catch (ParseException e) {
            return "Parse String to Date error,with pattern:"+pattern;
        }
    }

    @Function
    public static String formatDate(Object date){
        return formatDateBypattern(date,DEFAULT_DATE_FORMAT);
    }

    @Function
    public static String formatDateTime(Object date){
        return formatDateBypattern(date,DEFAULT_DATE_TIME_FORMAT);
    }

}
